package cn.com.nr.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.ApiOperation;
import cn.com.common.constants.Constants;
import cn.com.common.result.DataResult;
import cn.com.gas.entity.GasStationinfoEntity;
import cn.com.gas.service.GasStationinfoService;
import cn.com.nr.entity.NrCaminfoForecastEntity;
import cn.com.nr.entity.NrConcreteEndangerEntity;
import cn.com.nr.entity.NrDiggingsEndangerEntity;
import cn.com.nr.entity.NrStationinfoForecastEntity;
import cn.com.nr.service.NrCaminfoForecastService;
import cn.com.nr.service.NrConcreteEndangerService;
import cn.com.nr.service.NrDiggingsEndangerService;
import cn.com.nr.service.NrStationinfoForecastService;
import cn.com.system.entity.SysDept;
import cn.com.system.service.DeptService;
import cn.com.system.service.impl.HttpSessionService;
import cn.com.util.TsBqUtils;



/**
 * 摄像头预估列表
 *
 * @author shaochangyang
 * @email l2l84o7o5@live.com
 * @date 2025-04-04 20:06:34
 */
@Controller
@RequestMapping("/nr/stationforecast")
public class NrStationinfoForecastController {
    @Autowired
    private NrStationinfoForecastService nrStationinfoForecastService;
    @Autowired
    private NrDiggingsEndangerService nrDiggingsEndangerService;
    @Autowired
    private NrConcreteEndangerService nrConcreteEndangerService;
    
	@Autowired
	private NrCaminfoForecastService nrCaminfoForecastService;
	@Autowired
	private GasStationinfoService gasStationinfoService;
	@Autowired
	private DeptService deptService;
	@Autowired
	private HttpSessionService httpSessionService;
	
	@Value("${file.path}")
	private String filePath;
	@Value("${file.url}")
	private String fileUrl;
    
    
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@ApiOperation(value = "企业预估0级-信息")
	@PostMapping("/list3")
	@ResponseBody
	public DataResult list3(@RequestBody NrStationinfoForecastEntity nrStationinfoForecast) throws ParseException {
		String industry = nrStationinfoForecast.getIndustry();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date();
		
		String taxpayerCode = nrStationinfoForecast.getTaxpayerCode();
		String taxorgcode = nrStationinfoForecast.getTaxorgcode();

		String currentDeptId = httpSessionService.getCurrentDeptId();
		
		List<String> endangerIdList = new ArrayList<>();
		
		if(industry.equals("混凝土")||industry.equals("水泥制造")){
			LambdaQueryWrapper<NrConcreteEndangerEntity> queryWrapper = Wrappers.lambdaQuery();
			
			if (TsBqUtils.isNotNull(taxorgcode)) {
				queryWrapper.eq(NrConcreteEndangerEntity::getTaxorgcode, taxorgcode);
			} else {
				if (Constants.TAX_COUNTES.equals(TsBqUtils.getTaxOrgLevel(currentDeptId))) {
					// 县区局
					queryWrapper.eq(NrConcreteEndangerEntity::getTaxorgcode, currentDeptId);
				} else if (Constants.TAX_CITIES.equals(TsBqUtils.getTaxOrgLevel(currentDeptId))) {
					// 市局
					queryWrapper.like(NrConcreteEndangerEntity::getTaxorgcode, currentDeptId.substring(0, 5));
				} else {
					// 省局
				}
			}

			if (TsBqUtils.isNotNull(nrStationinfoForecast.getStationinfoName())) {
				queryWrapper.like(NrConcreteEndangerEntity::getName, nrStationinfoForecast.getStationinfoName());
			}
			
			if (TsBqUtils.isNotNull(taxpayerCode)) {
				queryWrapper.like(NrConcreteEndangerEntity::getTaxpayerCode, taxpayerCode);
			}
			queryWrapper.eq(NrConcreteEndangerEntity::getIndustry, industry);
			
			List<NrConcreteEndangerEntity> listEntity = nrConcreteEndangerService.list(queryWrapper);
			
			for (NrConcreteEndangerEntity entity : listEntity) {
				endangerIdList.add(entity.getId());
			}
			
		}else if(industry.equals("铁矿选矿")||industry.equals("铁矿采矿")){
			LambdaQueryWrapper<NrDiggingsEndangerEntity> queryWrapper = Wrappers.lambdaQuery();
			
			if (TsBqUtils.isNotNull(taxorgcode)) {
				queryWrapper.eq(NrDiggingsEndangerEntity::getTaxorgcode, taxorgcode);
			} else {
				if (Constants.TAX_COUNTES.equals(TsBqUtils.getTaxOrgLevel(currentDeptId))) {
					// 县区局
					queryWrapper.eq(NrDiggingsEndangerEntity::getTaxorgcode, currentDeptId);
				} else if (Constants.TAX_CITIES.equals(TsBqUtils.getTaxOrgLevel(currentDeptId))) {
					// 市局
					queryWrapper.like(NrDiggingsEndangerEntity::getTaxorgcode, currentDeptId.substring(0, 5));
				} else {
					// 省局
				}
			}

			if (TsBqUtils.isNotNull(nrStationinfoForecast.getStationinfoName())) {
				queryWrapper.like(NrDiggingsEndangerEntity::getName, nrStationinfoForecast.getStationinfoName());
			}
			
			if (TsBqUtils.isNotNull(taxpayerCode)) {
				queryWrapper.like(NrDiggingsEndangerEntity::getTaxpayerCode, taxpayerCode);
			}
			queryWrapper.eq(NrDiggingsEndangerEntity::getIndustry, industry);
			
			List<NrDiggingsEndangerEntity> listEntity = nrDiggingsEndangerService.list(queryWrapper);
			
			for (NrDiggingsEndangerEntity entity : listEntity) {
				endangerIdList.add(entity.getId());
			}
			
		}else{
			return DataResult.fail("industry入参不合法！");
			
		}
		if(TsBqUtils.isNull(endangerIdList)){
			return DataResult.fail("未查询到相关站点数据！");
		}
		Page page = new Page(nrStationinfoForecast.getPage(), nrStationinfoForecast.getLimit());
		LambdaQueryWrapper<GasStationinfoEntity> queryWrapper = Wrappers.lambdaQuery();
		queryWrapper.in(GasStationinfoEntity::getId, endangerIdList);
		IPage<GasStationinfoEntity> iPage = gasStationinfoService.page(page, queryWrapper);

		List<GasStationinfoEntity> records = iPage.getRecords();
		for (GasStationinfoEntity gasStationinfoEntity : records) {
			
			// 处理加油站 名称
			if (gasStationinfoEntity.getType().equals("group") || gasStationinfoEntity.getType().equals("domain")) {
				gasStationinfoEntity.setName(TsBqUtils.handleEndBeforeParentheses(gasStationinfoEntity.getName()));
			}
			// 税务机关
			if (TsBqUtils.isNotNull(gasStationinfoEntity.getTaxorgcode())) {
				SysDept sysDept = deptService.getById(gasStationinfoEntity.getTaxorgcode());
				gasStationinfoEntity.setTaxorgName(sysDept.getName());
			}

			// 计算累计金额
			BigDecimal gatherValueDecimal = new BigDecimal(0);
			BigDecimal forecastValueDecimal = new BigDecimal(0);
			
			BigDecimal gatherCalculatDecimal = new BigDecimal(0);
			BigDecimal forecastCalculatDecimal = new BigDecimal(0);
			
			BigDecimal offlineDecimal = new BigDecimal(0);
			
			String id = gasStationinfoEntity.getId();

			LambdaQueryWrapper<NrCaminfoForecastEntity> queryWrapper1 = Wrappers.lambdaQuery();
			queryWrapper1.eq(NrCaminfoForecastEntity::getStationinfoId, id);

			if (!StringUtils.isEmpty(nrStationinfoForecast.getCreateTimeStart())) {
				queryWrapper1.ge(NrCaminfoForecastEntity::getTime,nrStationinfoForecast.getCreateTimeStart().trim());
			}
			
			if (!StringUtils.isEmpty(nrStationinfoForecast.getCreateTimeEnd())) {
				queryWrapper1.le(NrCaminfoForecastEntity::getTime,nrStationinfoForecast.getCreateTimeEnd().trim());
			}

			List<NrCaminfoForecastEntity> list = nrCaminfoForecastService.list(queryWrapper1);

			for (NrCaminfoForecastEntity caminfoForecast : list) {
				String gatherValue = caminfoForecast.getGatherValue();
				BigDecimal _gatherValue = new BigDecimal(gatherValue);
				gatherValueDecimal = gatherValueDecimal.add(_gatherValue);

				String forecastValue = caminfoForecast.getForecastValue();
				BigDecimal _forecastValue = new BigDecimal(forecastValue);
				forecastValueDecimal = forecastValueDecimal.add(_forecastValue);

				String gatherCalculat = caminfoForecast.getGatherCalculat();
				BigDecimal _gatherCalculat = new BigDecimal(gatherCalculat);
				gatherCalculatDecimal = gatherCalculatDecimal.add(_gatherCalculat);

				String forecastCalculat = caminfoForecast.getForecastCalculat();
				BigDecimal _forecastCalculat = new BigDecimal(forecastCalculat);
				forecastCalculatDecimal = forecastCalculatDecimal.add(_forecastCalculat);
				
				String offlineTime = caminfoForecast.getOfflineTime();
				BigDecimal _offlineDecimal = new BigDecimal(offlineTime);
				offlineDecimal = offlineDecimal.add(_offlineDecimal);
				
			}

			gasStationinfoEntity.setGatherValue(gatherValueDecimal.toString());
			gasStationinfoEntity.setForecastValue(forecastValueDecimal.toString());
			
			gasStationinfoEntity.setGatherCalculat(gatherCalculatDecimal.toString());
			gasStationinfoEntity.setForecastCalculat(forecastCalculatDecimal.toString());
			
			if (offlineDecimal.compareTo(BigDecimal.ZERO) == 0 && gatherValueDecimal.compareTo(BigDecimal.ZERO) == 0 ) {
				Date parseStart = sdf.parse(nrStationinfoForecast.getCreateTimeStart() + " 00:00:00");
				Date parseEnd = sdf.parse(nrStationinfoForecast.getCreateTimeEnd() + " 23:59:59");

				int result = date.compareTo(parseEnd);
				int daysBetween = 0;
				
				boolean equals = nrStationinfoForecast.getCreateTimeStart().trim().equals(nrStationinfoForecast.getCreateTimeEnd().trim());
				if(!equals){
					if (result < 0) {
						// date 早
						daysBetween = daysBetween(parseStart, date);
					} else if (result > 0) {
						// date 晚
						daysBetween = daysBetween(parseStart, parseEnd);
					} else {
						// 
						daysBetween = 1;
					}
				}else{
					daysBetween = 1;
				}
				
				gasStationinfoEntity.setOfflineTime(String.valueOf(daysBetween * 24 * 60 * 60).replace("-", ""));

			} else {
				gasStationinfoEntity.setOfflineTime(offlineDecimal.toString());
			}
			
			// 计算  forecastValue1 gasLocation1 gasCoverage1 
			LambdaQueryWrapper<NrStationinfoForecastEntity> queryWrapper2 = Wrappers.lambdaQuery();
			queryWrapper2.eq(NrStationinfoForecastEntity::getStationinfoId, id);

			if (!StringUtils.isEmpty(nrStationinfoForecast.getCreateTimeStart())) {
				queryWrapper2.ge(NrStationinfoForecastEntity::getTime,nrStationinfoForecast.getCreateTimeStart().trim());
			
			}
			
			if (!StringUtils.isEmpty(nrStationinfoForecast.getCreateTimeEnd())) {
				queryWrapper2.le(NrStationinfoForecastEntity::getTime,nrStationinfoForecast.getCreateTimeEnd().trim());
				
			}

			List<NrStationinfoForecastEntity> list1 = nrStationinfoForecastService.list(queryWrapper2);
			if(TsBqUtils.isNotNull(list1)){
				
				BigDecimal forecastValueDecimal1 = new BigDecimal(0);
				BigDecimal amountDecimal = new BigDecimal(0);
				
				for (NrStationinfoForecastEntity _nrStationinfoForecast : list1) {
					String forecast = "0";
					String forecastValue1 = _nrStationinfoForecast.getForecastValue1();
					String forecastValue = _nrStationinfoForecast.getForecastValue();
					
					
					
					if(TsBqUtils.isNotNull(forecastValue1)){
						forecast = forecastValue1;
					}else if(TsBqUtils.isNotNull(forecastValue)){
						
					}
					
					BigDecimal _forecastValue = new BigDecimal(forecast);
					forecastValueDecimal1 = forecastValueDecimal1.add(_forecastValue);
					
				}
				
				gasStationinfoEntity.setForecastValue1(forecastValueDecimal1.toString());
				gasStationinfoEntity.setAmount(amountDecimal.toString());
			}
						
		}

		return DataResult.success(iPage);

	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@ApiOperation(value = "企业预估1级-信息")
	@PostMapping("/list2")
	@ResponseBody
	public DataResult list2(@RequestBody NrStationinfoForecastEntity nrStationinfoForecast) throws ParseException {

		/*String currentDeptId = httpSessionService.getCurrentDeptId();

		String stationinfoName = nrStationinfoForecast.getStationinfoName();

		String deptId = nrStationinfoForecast.getTaxorgcode();
		// 查询加油站
		LambdaQueryWrapper<GasStationinfoEntity> queryWrapperStationinfo = Wrappers.lambdaQuery();
		if (TsBqUtils.isNotNull(deptId)) {
			queryWrapperStationinfo.eq(GasStationinfoEntity::getType, "group");
			queryWrapperStationinfo.eq(GasStationinfoEntity::getIsAnalyse, "Y");
			queryWrapperStationinfo.eq(GasStationinfoEntity::getTaxorgcode, deptId);

		} else {
			if (Constants.TAX_COUNTES.equals(TsBqUtils.getTaxOrgLevel(currentDeptId))) {
				// 县区局
				queryWrapperStationinfo.eq(GasStationinfoEntity::getType, "group");
				queryWrapperStationinfo.eq(GasStationinfoEntity::getIsAnalyse, "Y");
				queryWrapperStationinfo.eq(GasStationinfoEntity::getTaxorgcode, currentDeptId);

			} else if (Constants.TAX_CITIES.equals(TsBqUtils.getTaxOrgLevel(currentDeptId))) {
				// 市局 
				queryWrapperStationinfo.eq(GasStationinfoEntity::getType, "group");
				queryWrapperStationinfo.eq(GasStationinfoEntity::getIsAnalyse, "Y");
				queryWrapperStationinfo.like(GasStationinfoEntity::getTaxorgcode, currentDeptId.substring(0, 5));
			} else{
				// 省局
			}
		}

		if (TsBqUtils.isNotNull(stationinfoName)) {
			queryWrapperStationinfo.like(GasStationinfoEntity::getName, stationinfoName);
		}
		List<GasStationinfoEntity> listGasStationinfo = gasStationinfoService.list(queryWrapperStationinfo);
		List<String> stationinfoIdList = new ArrayList<>();
		for (GasStationinfoEntity stationinfo : listGasStationinfo) {
			String stationinfoId = stationinfo.getId();
			stationinfoIdList.add(stationinfoId);
		}*/

		Page page = new Page(nrStationinfoForecast.getPage(), nrStationinfoForecast.getLimit());
		LambdaQueryWrapper<NrStationinfoForecastEntity> queryWrapper = Wrappers.lambdaQuery();

		// 查询条件示例
		if (TsBqUtils.isNotNull(nrStationinfoForecast.getStationinfoId())) {
			queryWrapper.eq(NrStationinfoForecastEntity::getStationinfoId, nrStationinfoForecast.getStationinfoId());
		}

		if (!StringUtils.isEmpty(nrStationinfoForecast.getCreateTimeStart())) {
			/*queryWrapper.ge(GasStationinfoForecastEntity::getCreateTime,
					sdf.parse(gasStationinfoForecast.getCreateTimeStart() + " 00:00:00"));*/
			queryWrapper.ge(NrStationinfoForecastEntity::getTime,nrStationinfoForecast.getCreateTimeStart().trim());

			
		}
		
		if (!StringUtils.isEmpty(nrStationinfoForecast.getCreateTimeEnd())) {
			/*queryWrapper.le(GasStationinfoForecastEntity::getCreateTime,
					sdf.parse(gasStationinfoForecast.getCreateTimeEnd() + " 23:59:59"));*/
			queryWrapper.le(NrStationinfoForecastEntity::getTime,nrStationinfoForecast.getCreateTimeEnd().trim());

		}
		
		queryWrapper.orderByDesc(NrStationinfoForecastEntity::getTime);

		IPage<NrStationinfoForecastEntity> iPage = nrStationinfoForecastService.page(page, queryWrapper);
		List<NrStationinfoForecastEntity> records = iPage.getRecords();
		for (NrStationinfoForecastEntity stationinfoForecast : records) {
			
			// 设置加工的获取加油区
						
			String stationinfoId = stationinfoForecast.getStationinfoId();
			String taxorgcode = stationinfoForecast.getTaxorgcode();
			GasStationinfoEntity stationinfo = gasStationinfoService.getById(stationinfoId);

			// String gasLocation = stationinfo.getGasLocation();
			// String gasCoverage = stationinfo.getGasCoverage();
			
			SysDept sysDept = deptService.getById(taxorgcode);
			String taxName = taxorgcode;
			if (TsBqUtils.isNotNull(sysDept)) {
				taxName = sysDept.getName();
			}

			stationinfoForecast.setStationinfoName(TsBqUtils.handleEndBeforeParentheses(stationinfo.getName()));
			stationinfoForecast.setTaxorgName(taxName);

			// String forecastValue = stationinfoForecast.getForecastValue();
		}

		return DataResult.success(iPage);
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@ApiOperation(value = "企业预估2级-信息")
	@PostMapping("/list1")
	@ResponseBody
	public DataResult list1(@RequestBody NrCaminfoForecastEntity nrStationinfoForecast) {

		Page page = new Page(nrStationinfoForecast.getPage(), nrStationinfoForecast.getLimit());
		LambdaQueryWrapper<NrCaminfoForecastEntity> queryWrapper = Wrappers.lambdaQuery();
		// 查询条件示例
		queryWrapper.eq(NrCaminfoForecastEntity::getStationinfoId, nrStationinfoForecast.getStationinfoId());
		queryWrapper.eq(NrCaminfoForecastEntity::getTime, nrStationinfoForecast.getTime());
		queryWrapper.orderByDesc(NrCaminfoForecastEntity::getStationinfoId);
		IPage<NrCaminfoForecastEntity> iPage = nrCaminfoForecastService.page(page, queryWrapper);

		List<NrCaminfoForecastEntity> records = iPage.getRecords();
		for (NrCaminfoForecastEntity caminfoForecast : records) {
			String camid = caminfoForecast.getCamId();
			GasStationinfoEntity stationinfo = gasStationinfoService.getById(camid);
			if(TsBqUtils.isNotNull(stationinfo)){
				caminfoForecast.setCamName(stationinfo.getName());

			}
		}
		return DataResult.success(iPage);
	}
	
	public static int daysBetween(Date date1, Date date2) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date1);
		long time1 = cal.getTimeInMillis();
		cal.setTime(date2);
		long time2 = cal.getTimeInMillis();
		long between_days = (time2 - time1) / (1000 * 3600 * 24);
		return Integer.parseInt(String.valueOf(between_days));
	}
	
}
